package bean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import dao.DoctorDAO;
import dao.DoctorSpecialtyDAO;
import dao.JPA;
import dao.UserDAO;
import entity.Doctor;
import entity.DoctorSpecialty;

@Named
@RequestScoped
public class EditDoctorBean {

	@Inject @JPA
	private DoctorDAO doctorDAO;
	@Inject @JPA
	private DoctorSpecialtyDAO doctorSpecialtyDAO;	
	@Inject @JPA
	private UserDAO userDAO;
	private Doctor doctor;
	private List<DoctorSpecialty> doctorSpecialtyList;
	private boolean editMode;
	
	public EditDoctorBean() {
		doctor = new Doctor();		
	}
	
	@PostConstruct
	private void init() {		
		doctor.setUser(userDAO.selectUserByName(FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName()));
		Doctor doc = null;
		if((doc = doctorDAO.selectDoctorByUserId(doctor.getUser().getId())) != null) {
			doctor =  doc;
			editMode = true;
		}
		doctorSpecialtyList = doctorSpecialtyDAO.findAll();
	}
	
	public String editDoctor() {
		if(editMode)
			doctorDAO.merge(doctor);			
		else 
			doctorDAO.persist(doctor);
		FacesContext facesContext = FacesContext.getCurrentInstance();		
		facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Your profile is updated", "Your profile is updated"));		
		return "back";
	}
	
	public Doctor getDoctor() {
		return doctor;
	}
	
	public List<DoctorSpecialty> getDoctorSpecialtyList() {
		return doctorSpecialtyList;
	}
	
	public boolean isEditMode() {
		return editMode;
	}
	
}
